from django.shortcuts import render
from rest_framework.views import APIView
from random import randint
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework import status


from . import constants
from celery_tasks.sms.tasks import send_sms_code

# Create your views here.


class SMSCodeView(APIView):
    """短信验证码"""

    def get(self, request, mobile):
        # 2.创建redis连接对象
        redis_conn = get_redis_connection('verify_codes')
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return Response({'message': '手机频繁发送消息'}, status=status.HTTP_400_BAD_REQUEST)
        # 1.生成验证码
        sms_code = '%06d' % randint(0, 999999)
        print("短信验证码：%d", sms_code)
        # 创建redis管道，将多次redis操作装入管道中，将来一次性执行
        pl = redis_conn.pipeline()
        # 3.把验证码发送到redis数据库
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        # 执行管道
        pl.execute()
        # 4.利用容联云发送短信验证码
        # CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60], 1)
        # 出发异步任务，将异步任务加入到celery任务队列
        send_sms_code.delay(mobile, sms_code)  # 触发异步任务，注意.delay
        # 5.响应
        return Response({'message': 'OK,验证码:' + str(sms_code)})
